import { push as _push } from 'redux-first-history';
import { store } from "../store";
import { useEffect } from 'react';
import { SAVE_BREADCRUMB, SAVE_PERMISSIONS } from '@/reducers/common';
import { message } from 'antd';
import { showPermissions } from '@/apis/user';
export const formLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
    },
};
//补0
export const makeUpHours = (str: string | number, len: number = 2) => {
    str = str + '';
    if (str.length < len) {
        str = '0' + str;
    }
    return str;
};
// 格式化时间
export const formatTimeToStr = (time: string | number) => {
    try {
        if (!time) return time;
        let date = new Date(time);
        const y = date.getFullYear(),
            m = date.getMonth() + 1,
            d = date.getDate(),
            h = date.getHours(),
            mi = date.getMinutes(),
            s = date.getSeconds();
        let da = [y, makeUpHours(m), makeUpHours(d)],
            ti = [makeUpHours(h), makeUpHours(mi), makeUpHours(s)];
        return da.join('-') + ' ' + ti.join(':');
    } catch (e) {
        return '';
    }
};

export function formatMoney(text: number) {
    if (!text && text != 0) {
        return "-";
    } else {
        return "￥" + text.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
}

export function download(url: string, downloadName = "excel") {
    if (url && Object.prototype.toString.call(url) === "[object String]") {
        const a = document.createElement("a");
        a.href = encodeURI(url);
        a.download = downloadName;
        a.click();
    }
}

export function dispatchWithPromise(args: any) {
    return new Promise((resolve, reject) => {
        store.dispatch({ ...args, resolve, reject });
    });
}
//设置面包屑组件
function GetBreadcRumb(data: (string | { [key: string]: string | undefined })[]) {
    useEffect(() => {
        dispatchWithPromise({ type: SAVE_BREADCRUMB, data });
    }, [])
}
export const getBreadcRumb = GetBreadcRumb
export const tablePaginationConfig = {
    pageSizeOptions: ["10", "20", "30", "40", "50"],
    showTotal: (total: number, range: number[]) => {
        return `总共${total}条，当前第${range[0]}至${range[1]}条`;
    },
    showSizeChanger: true,
    showQuickJumper: true,
};
//乘法
export function accMul(arg1: number, arg2: number) {
    let m = 0;
    const s1 = arg1.toString();
    const s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
        console.log(e)
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
        console.log(e)
    }
    return (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
    );
}
export function htmlEncodeByRegExp(str: string) {
    let temp = "";
    if (str.length == 0) return "";
    temp = str.replace(/&/g, "&amp;");
    temp = temp.replace(/</g, "&lt;");
    temp = temp.replace(/>/g, "&gt;");
    temp = temp.replace(/\s/g, "%20");
    temp = temp.replace(/\\'/g, "&#39;");
    temp = temp.replace(/\\"/g, "&quot;");
    return temp;
}
/**
 * @name 下载文件
 * @param filename 文件名（必填）
 * @param data 地址或blobPart
 */
export const downloadFile = (filename: string, data: string | Blob) => {
    if (!filename) return console.warn('请输入文件名');
    const a = document.createElement('a');
    a.target = '_blank';
    a.download = filename;
    a.href = typeof data === 'string' ? data : URL.createObjectURL(data);
    a.click();
    URL.revokeObjectURL(a.href);
};
// 复制文本内容
export const copyText = (content: string) => {
    // 复制结果
    let copyResult = true
    // 设置想要复制的文本内容
    const text = content || '';
    // 判断是否支持clipboard方式
    if (window.navigator.clipboard) {
        // 利用clipboard将文本写入剪贴板（这是一个异步promise）
        window.navigator.clipboard.writeText(text).then(() => {
            message.success("复制成功");
            console.log('复制成功');
            // 返回复制操作的最终结果
            return copyResult;
        }).catch((err) => {
            copyResult = false
            console.log('复制失败', err);
            console.log('复制失败');
            // 返回复制操作的最终结果
            return copyResult;
        })
    } else {
        // 不支持clipboard方式 则采用document.execCommand()方式
        // 创建一个input元素
        let inputDom = document.createElement('textarea');
        // 设置为只读 防止移动端手机上弹出软键盘  
        inputDom.setAttribute('readonly', 'readonly');
        // 给input元素赋值
        inputDom.value = text;
        // 将创建的input添加到body
        document.body.appendChild(inputDom);
        // 选中input元素的内容
        inputDom.select();
        // 执行浏览器复制命令
        // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签中的内容）
        // Input要在正常的编辑状态下原生复制方法才会生效
        const result = document.execCommand('copy')
        // 判断是否复制成功
        if (result) {
            console.log('复制成功');
            message.success("复制成功");
        } else {
            message.error("复制失败")
            console.log('复制失败');
            copyResult = false
        }
        // 复制操作后再将构造的标签 移除
        document.body.removeChild(inputDom);
        // 返回复制操作的最终结果
        return copyResult;
    }

}

export const getGlobalTableState = {
    loading: false,
    list: [],
    pageNum: 1,
    pageSize: 10,
    totalPage: 0,
    totalSize: 0,
};

export const uploadQiniuUrl: string = "https://upload.qiniup.com/";

//获取第一条权限并返回需要登陆的页面
export async function getFirstPermission(sideMenu: SideMenuItemList) {
    //获取权限
    let res2 = await showPermissions({})
    dispatchWithPromise({
        type: SAVE_PERMISSIONS,
        data: res2.data
    })
    let permissions = res2.data
    let firstFirst = '/home'
    if (sideMenu) {
        for (let i in sideMenu) {
            if (sideMenu[i].children) {
                let children = sideMenu[i].children
                for (let j in children) {
                    if (children[parseInt(j)]) {
                        for (let t in permissions) {
                            if (permissions[t].permissionKey == children[parseInt(j)].permission && children[parseInt(j)].path) {
                                firstFirst = children[parseInt(j)].path || ''
                                // console.log(firstFirst)
                                return children[parseInt(j)].path || ''
                            }
                        }
                    }
                }
            }
        }
    }
    return firstFirst
}

export const push = (path: string) => {
    store.dispatch(_push(path));
}
//全屏
export function fullScreen() {
    const element = document.body as any;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen();
    }
}

//页面自适应
export function setmultiple() {
    const innerWidth = window.innerWidth
    const innerHeight = window.innerHeight
    const radioWidth = innerWidth / 1920
    const radioHeight = innerHeight / 1080
    const multiple = radioHeight > radioWidth ? radioWidth : radioHeight
    document.body.style.setProperty('--multiple', String(multiple));
}


//数组分裂
export const arrFlat = (arr: Array<never>, index: number) => {
    const newarr = []
    for (let i = 0; i < index; i++) {
        newarr[i] = arr
    }
    return newarr
}

/**
 * 下载文件
 * @param {*} data 对象
 * @param {*} fileName 文件名
 */
export const downLink = function (data: any, fileName: string) {
    const blob = new Blob([data], { type: "application/vnd.ms-excel" }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
    const downloadElement = document.createElement("a");
    const href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = fileName; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
}


/**
 * @function 数组对象转化成数组
 */
export const ArrayObjectToArray = function (arr: []) {
    const newarr = []
    for (const i in arr) {

        newarr.push(Object.values(arr[i])[0])
    }
    return newarr
}


/**
 * @function 获取传入参数的类型
 * @param {any} any 参数
 */
export const getObject = function (any: never) {
    const str = Object.prototype.toString.call(any).split(' ')[1]
    return str.substr(0, str.length - 1)
}

//获取年龄
export function getAge(idCard: string) {
    idCard = idCard + ''
    const oldyear = parseInt(idCard.substring(6, 10))
    const oldmonth = parseInt(idCard.substring(10, 12))
    const oldday = parseInt(idCard.substring(12, 14))
    const year = new Date().getFullYear()
    const month = new Date().getMonth() + 1
    const day = new Date().getDate()
    let age = year - oldyear
    if (month < oldmonth) {
        age = age - 1
    }
    if (month == oldmonth) {
        if (day < oldday) {
            age = age - 1
        }
    }
    return age + ''
}